using System;
using System.Net;
using CodePlex.TfsLibrary.ObjectModel;

namespace CodePlex.CodePlexClientLibrary
{
    [Command("workspace", "TFS workspace operations", MinArgs = 2, MaxArgs = 3, UsageSummary = "<tfsUrl> <operation> [args] [options]",
        UsageDescription = @"Valid operations:
  list             : show all your TFS workspaces
  delete <arg>     : deletes a TFS workspace")]
    public class WorkspaceCommand : AuthenticatedCommand
    {
        readonly ISourceControlService service;

        public WorkspaceCommand(ISourceControlService service)
        {
            this.service = service;
        }

        void DeleteWorkspace(string url,
                             string workspaceName)
        {
            service.DeleteWorkspace(url, GetCredentials(url), workspaceName);
        }

        public override void Execute()
        {
            string url = Arguments[0];
            string operation = Arguments[1].ToLowerInvariant();

            switch (operation)
            {
                case "delete":
                    if (Arguments.Count < 3)
                        throw new Exception("Must specify workspace to delete.");
                    DeleteWorkspace(url, Arguments[2]);
                    break;

                case "list":
                    ListWorkspaces(url);
                    break;

                default:
                    throw new Exception("Unknown workspace operation: '" + operation + "'");
            }
        }

        ICredentials GetCredentials(string url)
        {
            if (!string.IsNullOrEmpty(Username))
            {
                CredentialCache cache = new CredentialCache();
                cache.Add(new Uri(url), "Basic", new NetworkCredential(Username, Password));
                return cache;
            }

            return null;
        }

        void ListWorkspaces(string url)
        {
            WorkspaceInfo[] workspaces = service.GetWorkspaces(url, GetCredentials(url), WorkspaceComputers.AllComputers);

            foreach (WorkspaceInfo workspace in workspaces)
                Console.WriteLine(workspace.Name);
        }
    }
}